<template>
  <div class="container">
    <div class="login">
      <img src="../assets/logo.png" alt="">
      <el-form :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input prefix-icon="iconfont icon-user" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" prefix-icon=" iconfont icon-lock_fill" v-model="loginForm.password"></el-input>
        </el-form-item>
        <div class="btn">
          <el-button @click="resetBtn" type="info">重置</el-button>
          <el-button @click="loginSubmit" type="primary">登陆</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    resetBtn() {
      this.$refs.loginFormRef.resetFields()
    },
    loginSubmit() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('login', this.loginForm)
        if (res.meta.status !== 200) {
          return this.$message.error('登陆失败')
        }
        this.$message.success('登陆成功')
        this.$router.push('/home')
        window.sessionStorage.setItem('token', res.data.token)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: #2b4b6b;
}
.login {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 450px;
  height: 300px;
  transform: translate(-50%, -50%);
  background-color: #fff;
  border-radius: 5px;

  img {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 100px;
    height: 100px;
  }
}
.el-form {
  position: absolute;
  bottom: 10px;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}
.btn {
  display: flex;
  justify-content: flex-end;
}
</style>
